<html>
	<head>
        <meta  charset="utf-8" />
         <title>Manage Graph</title>
        <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
		<script src="sigma.min.js" type="text/javascript"></script>
        <script src="testInputGraph.js" type="text/javascript"></script>

        <script type="text/javascript">
            function getListGraph() {
                $.get("http://localhost:8080/RESTfulExample/rest/graph/getallgraph").done(function (result) {
                    var resultJson = {};
                    try {
                        resultJson = eval('(' + result.jsonmapper["@json"] + ')');
                        var elsel = document.getElementById("listGraph");

                        for (var i = 0; i < resultJson.graphs.length; i++) {
                            var elopt = document.createElement('option');
                            elopt.text = resultJson.graphs[i].name;
                            elopt.value = resultJson.graphs[i].name;

                            if (i == 0) {
                                getFirstGraph(resultJson.graphs[i].name);
                            }

                            try {
                                elsel.add(elopt, null);
                            }
                            catch (err) {
                                elsel.add(elopt);
                            }
                        }

                        if (resultJson.graphs.length == 0) {
                            $("#listGraph").val("Empty");
                            var elopt = document.createElement('option');
                            elopt.text = "Empty";
                            elopt.value = 1;
                            try {
                                elsel.add(elopt, null);
                            }
                            catch (err) {
                                elsel.add(elopt);
                            }
                        }
                    }
                    catch (err) {
                        alert(err);
                    }
                }).fail(function (err) {
                    alert(err);
                });
            }

            function getFirstGraph(graphName) {
                $.get("http://localhost:8080/RESTfulExample/rest/graph/get/graphname=" + graphName).done(function (result) {
                    
	                var jsonResult;
	                try{
	                	jsonResult = eval('(' + result.jsonmapper["@json"] + ')');
	                }
	                catch (error)
	                {
	                	alert("Graph data is invalid");
	                }
	                
	                if (jsonResult.method == undefined) {
	                    $("#textJson").val(unescape(result.jsonmapper["@json"]));
	                    onClickViewGraph();
	                }
	                else {
	                    alert("Graph is not available");
	                    location.reload();
	                }
                }).fail(function (err) {
                    alert(err);
                });
            }

            function onClickViewGraph() {
                try {
                    sigInst.emptyGraph();
                    var jsonData = {};
                    try {
                        jsonData = eval('(' + $("#textJson").val() + ')');
                        var testGraph = new testInputGraph(jsonData);
                        if (!testGraph.test()) {
                            return false;
                        }
                    }
                    catch (err) {
                        alert(err);
                    }
                    
                    getLayout(jsonData);
                    for (var i = 0; jsonData.nodes != undefined && i < jsonData.nodes.length; i++) {
                        sigInst.addNode(jsonData.nodes[i].id, {
                            label: jsonData.nodes[i].name,
                            color: jsonData.nodes[i].color != undefined ? jsonData.nodes[i].color : "#ff0000",
                            x: jsonData.nodes[i].x,
                            y: jsonData.nodes[i].y
                        });
                    }

                    for (var i = 0; jsonData.edges != undefined && i < jsonData.edges.length; i++) {
                        sigInst.addEdge(jsonData.edges[i].name, jsonData.edges[i].from, jsonData.edges[i].to);
                    }

                    sigInst.draw();
                    

                } catch (err) {
                    alert(err);
                    return false;
                }
                return true;
            }

            function getLayout(data) {
                var nodeCount = data.nodes.length;
                var immediateNodes = new Array();
                for (var i = 0; i < nodeCount; i++) {
                    var node = {};
                    node.id = data.nodes[i].id;
                    node.name = data.nodes[i].name;
                    node.x = 0;
                    node.y = 0;

                    immediateNodes.push(node);
                }

                var sqrt = Math.sqrt(nodeCount);
                var numRows = Math.floor(sqrt);
                var numCols = Math.ceil(sqrt);

                if (numRows * numCols < nodeCount) {
                    numRows++;
                }

                var xInc = 0.15;
                var yInc = 0.15;
                var idx = 0;

                for (var i = 0; i < numRows; i++) {
                    for (var j = 0; j < numCols; j++) {
                        idx = i * numCols + j;
                        if (idx >= nodeCount)
                            break;
                        var node = immediateNodes[idx];
                        node.x = xInc * (j + 1);
                        node.y = yInc * (i + 1);
                    }
                }

                data.nodes = immediateNodes;
            }


            var sigInst;
            window.onload = function () {

                getListGraph();

                var sigNode = document.getElementById("graph");
                sigInst = sigma.init(sigNode).drawingProperties({
                    defaultLabelColor: '#ccc',
                    font: 'Arial',
                    edgeColor: 'source',
                    defaultEdgeType: 'curve'
                }).graphProperties({
                    minNodeSize: 1,
                    maxNodeSize: 10
                });


                $("#textJson").keydown(function (e) {
                    if (e.keyCode === 9) { // tab was pressed
                        // get caret position/selection
                        var start = this.selectionStart;
                        var end = this.selectionEnd;

                        var $this = $(this);
                        var value = $this.val();

                        // set textarea value to: text before caret + tab + text after caret
                        $this.val(value.substring(0, start)
                    + "\t"
                    + value.substring(end));

                        // put caret at right position again (add one for the tab)
                        this.selectionStart = this.selectionEnd = start + 1;

                        // prevent the focus lose
                        e.preventDefault();
                    }
                });


                $("#viewgraph").click(onClickViewGraph);

                $("#listGraph").change(function () {
                    getFirstGraph($("#listGraph").val());
                });

                //handle event btn
                var isCanRequest = true;

                $("#newbtn").click(function (e) {
                    location.href = "newgraph.html";
                });

                $("#deletebtn").click(function (e) {
                    var btn = this;
                    btn.disabled = true;
                   
                    $.ajax({
                        url: "http://localhost:8080/RESTfulExample/rest/graph/delete/graphname=" + $("#listGraph").val(),
                        type: 'DELETE',
                        success: function (result) {
                            var jsonResult = eval('(' + result.jsonmapper["@json"] + ')');
                            alert(jsonResult.method + ": " + jsonResult.value);
                            location.reload();
                            btn.disabled = false;
                        }
                    }).fail(function (err) {
                        alert("Can't connect to server!");
                        btn.disabled = false;
                    });
                });



                $("#updatebtn").click(function (e) {

                    if (!onClickViewGraph()) {
                        return;
                    }

                    var btn = this;
                    btn.disabled = true;
                    var jsonData;

                    try {
                        jsonData = eval('(' + $("#textJson").val() + ')');
                        if ($("#listGraph").val() != jsonData.name) {
                            btn.disabled = false;
                            alert("Can't change graph name!");
                            return;
                        }

                        $.ajax({
                            url: "http://localhost:8080/RESTfulExample/rest/graph/update/graphname=" + jsonData.name + "&graphdescription=" + escape($("#textJson").val()),
                            type: 'PUT',
                            success: function (result) {
                                var jsonResult = eval('(' + result.jsonmapper["@json"] + ')');
                                alert(jsonResult.method + ": " + jsonResult.value);
                                btn.disabled = false;
                                onClickViewGraph();
                            }
                        }).fail(function (err) {
                            alert("Can't connect to server!");
                            btn.disabled = false;
                        });
                    }
                    catch (err) {
                        alert(err);
                        btn.disabled = false;
                    }
                }

		        );
            }    
			
		</script>
	</head>
	<body>
        <div id="">
            
            <div id="jsontab" style="float:left; width:40%; height: 500px">
                <div style="padding:10px">
                    <div style="width:100%">
                        <div style="float:left">Graph Json: </div>
                        <div style="float:right">List Graph: <select id="listGraph"></select></div>
                    </div>
                    <div>
                        <textarea id="textJson" style="width:100%; height: 430px;" wrap="off"></textarea>
                    </div>
                    <div>
                        <div style="float:right">
                            <button id="viewgraph" style="margin:5px">View Graph</button>
                        </div>

                        <div style="float:right">
                            <button id="updatebtn" style="margin:5px">Update Graph</button>
                        </div>

                         <div style="float:right">
                            <button id="deletebtn" style="margin:5px">Delete Graph</button>
                        </div>

                        <div style="float:right">
                            <button id="newbtn" style="margin:5px">New Graph</button>
                        </div>

                    </div>
                </div>
            </div>
		    
            <div id="graphtab" style="float:left; width: 60%; height:500px">
                <div id="graph" style="margin:30px 10px 40px 10px;background-color:Black; height:430px"></div>
            </div>
	    </div>
    </body>
</html>